<template>
	<view class="">
		<view class="form-bx">
			<u--form :model="form" ref="uForm" :errorType="['toast']" labelWidth="100">
				<view class="gap">客户信息</view>
				<u-form-item label="选择客户" prop="userName" @click="!isEdit?$u.route('/pages/selectPage/client', {isRadio: true}):''">
						<view class="">
							<text>{{form.userName}}</text>
							<text class="fsize-24 line-gray" v-if="form.userId">({{form.userMobile}})</text>
							<text class="text-pla" v-else>请选择</text>
						</view>
						<u-icon slot="right" name="arrow-right"/>
				</u-form-item>
				<view class="gap">消费信息</view>
				<u-form-item label="订单类型" prop="orderTypeName" borderBottom @click="!isEdit?showOT = true:''">
					<u-input border="none" v-model="form.orderTypeName" placeholder="请选择" disabledColor="#fff" disabled />
					<u-icon slot="right" name="arrow-right"/>
				</u-form-item>
				<u-form-item label="订单明细">
					<view class="flex justify-between align-center" v-if="form.items.length === 0" @click="addOrderItems">
						<u-input border="none" placeholder="请添加" disabledColor="#fff" disabled />
						<u-icon name="arrow-right" color="#606266" size="16"/>
					</view>
					<view class="order-list" v-else>
						<!-- 项目 -->
						<view v-if="form.orderType === 11">
							<view v-for="(pIm, pIx) in form.items" :key="pIx">
								<view class="pb-20 border-b" :class="pIx > 0?'pt-20':''">
									<view @click="addOrderItems">{{pIm.name}}</view>
									<view class="mt-10">
										<text class="line-red">￥{{pIm.price}}</text>
										<text class="line-grey fsize-22 ml-30">x{{pIm.nums}}</text>
									</view>
								</view>
								<view>
									<view class="flex justify-between align-center border-b pt-20 pb-20" 
										@click="$u.route('/pages/selectPage/staff',{index: pIx, type: '1'})">
										<text v-if="pIm.staffId === 0" class="fsize-24 text-pla">请选择服务人员</text>
										<text v-else class="fsize-24">{{pIm.staffName}}</text>
										<u-icon name="arrow-right" color="#606266" size="16" />
									</view>
									<view class="flex justify-between align-center border-b pt-20 pb-20"
										@click="$u.route('/pages/selectPage/staff',{index: pIx, type: '2'})">
										<text v-if="$u.test.isEmpty(pIm.salerId)" class="fsize-24 text-pla">请选择销售人员(选)</text>
										<text v-else class="fsize-24">{{pIm.salerName}}</text>
										<u-icon name="arrow-right" color="#606266" size="16" />
									</view>
									<view class="flex justify-between align-center border-b pt-20 pb-20" @click="selDataTime(pIx)">
										<text v-if="!pIm.appointmentTime" class="fsize-24 text-pla">请选择预约时间(选)</text>
										<text v-else class="fsize-24">{{pIm.appointmentTime}}</text>
										<u-icon name="arrow-right" color="#606266" size="16" />
									</view>
								</view>
							</view>
						</view>
						<!-- 商品 -->
						<view class="" v-else>
							<view class="" v-for="(gIm, gIx) in form.items" :key="gIx" @click="addOrderItems">
								<view class="flex justify-between align-center">
									<view class="pb-20" :class="gIx > 0?'pt-20':''">
										<view>{{gIm.name}}</view>
										<view class="mt-10 flex align-center">
											<text class="line-red">￥{{gIm.price || gIm.salePrice}}</text>
											<text class="line-grey fsize-22 ml-30">x{{gIm.nums}}</text>
											<!-- <view class="ml-30" @click.stop="" v-if="form.orderType === 12">
												<u-number-box v-model="gIm.nums" @change="event=>onChangePnm(gIx, event)">
													<view slot="minus" class="minus">
														<u-icon name="minus" size="12"></u-icon>
													</view>
													<text slot="input" class="input">{{gIm.nums}}</text>
													<view slot="plus" class="plus">
														<u-icon name="plus" color="#FFFFFF" size="12"></u-icon>
													</view>
												</u-number-box>
											</view> -->
										</view>
									</view>
									<u-icon name="arrow-right" color="#606266" size="16" />
								</view>
								<view 
									class="flex justify-between align-center border-b border-t pt-20 pb-20"
									@click.stop="$u.route('/pages/selectPage/staff',{index: gIx, type: '2'})">
									<text v-if="$u.test.isEmpty(gIm.salerId)" class="fsize-24 text-pla">请选择销售人员(选)</text>
									<text v-else class="fsize-24">{{gIm.salerName}}</text>
									<u-icon name="arrow-right" color="#606266" size="16" />
								</view>
							</view>
						</view>
					</view>
				</u-form-item>
				<view class="pl-20 pr-20 mt-20" v-if="form.consumeAmout>0">
					<view class="padding-20 flex justify-between align-center bg-white fsize-30 border-radius-10 border-b">
						<view class="flex">
							<uni-icons custom-prefix="iconfont" type="icon-shishidaikou" size="22" color="#f37b1d" />
							<text>【{{form.cardItemName}}】</text>
						</view>
						<text class="line-red">-{{form.consumeAmout}}元</text>
					</view>
					<view class="padding-20 flex justify-between align-center bg-white fsize-30 border-radius-10" v-if="form.discountAmout > 0">
						<view class="flex">
							<uni-icons custom-prefix="iconfont" type="icon-percentage" size="22" color="#f37b1d" />
							<text>【{{form.schemeName}}】</text>
						</view>
						<text class="line-red">-{{form.discountAmout}}元</text>
					</view>
				</view>
				<view v-if="form.userName">
					<view class="gap">赠送项目</view>
					<view class="padding-20 bg-white mb-10 fsize-30" v-for="(gift, giftIx) in form.gives" :key="giftIx">
						<view class="flex justify-between align-center pb-20">
							<view class="flex align-center">
								<uni-icons custom-prefix="iconfont" type="icon-zeng" size="26" color="#e54d42" />
								<text class="ml-10">{{gift.name}}</text>
							</view>
							<u-number-box v-model="gift.nums" @change="setGiftNums" :name="giftIx" :min="0">
								<view slot="minus">
									<u-icon name="minus-circle" size="24" color="#e54d42"></u-icon>
								</view>
								<text slot="input" class="width-80 text-align-center">{{gift.nums}}</text>
								<view slot="plus">
									<u-icon name="plus-circle" size="24" color="#e54d42"></u-icon>
								</view>
							</u-number-box>
						</view>
						<view class="pt-20 border-t flex justify-between align-center">
							<text>有效期至</text>
							<view class="flex align-center" @click="setDate(giftIx)">
								<text class="mr-10">{{gift.validityDate}}</text>
								<u-icon name="arrow-right" size="16" color="#606266"></u-icon>
							</view>
						</view>
					</view>
					<view class="padding-20 bg-white line-red text-align-center fsize-28" @click="$u.route('/pages/selectPage/giftItems')">+添加赠送</view>
				</view>
				<view class="gap">结算信息</view>
				<u-form-item label="优惠价格" prop="discountAmount" borderBottom>
					<u-input 
						border="none" 
						type="number" 
						v-model="form.discountAmount" 
						@blur="setDiscountAmount" 
						placeholder="请输入优惠价格" 
						:disabled="form.items.length===0" 
						disabledColor="#fff" 
					/>
				</u-form-item>
				<u-form-item label="应收款" prop="realAmout" @click="$u.route('/pages/staff/list/list');">
					<u-input border="none" type="number" v-model="form.realAmout" disabledColor="#fff" disabled />
				</u-form-item>
				<view class="gap">订单备注</view>
				<u-form-item>
					<u-input border="none" v-model="form.remark" placeholder="请输入备注(选填)" />
				</u-form-item>
			</u--form>
		</view>
		<view class="ubtn">
			<u-button type="error" @click="submit" text="开单并收款" size="large" />
		</view>
		<u-picker :show="showOT" :columns="ots" keyName="name" :immediateChange="true"
			@confirm="changeOT" :closeOnClickOverlay="true" @cancel="showOT=false"/>
		<u-toast ref="uToast"></u-toast>
		<u-datetime-picker
			:show="showTimePicker"
			v-model="datetime"
			mode="datetime"
			@cancel = "showTimePicker=false"
			@confirm="onConfirmDataTime"
		></u-datetime-picker>
		<u-datetime-picker
			:show="showDatePicker"
			v-model="dateVal"
			mode="date"
			@cancel = "showDatePicker=false"
			@confirm="onConfirmData"
		></u-datetime-picker>
	</view>
</template>

<script>
	import date from '@/common/date.js'
	import getDateTime from '@/common/getDataTime.js'
	import { mapState } from 'vuex'
	export default {
		data() {
			return {
				showDatePicker: false,
				isEdit:false,
				showOT: false,
				showTimePicker: false,
				datetime: '',
				dateVal: date.getDate(366),
				dtIndex: null,
				Dix: null,
				qrcUrl: '',
				showQRC: false,
				ots: [
					[
						{ name: '项目', value: 11 },
						{ name: '商品', value: 1 },
						{ name: '疗程卡', value: 12 }
					]
				],
				cIndex: 0,
				isShowCalendar: false,
				timeRadios: [],
				dateList: [],
				realAmout: 0,
				form: {
					userName: '',
					userId: null,
					storeId: null,
					orderType: null,
					orderTypeName: '',
					remark:'',
					items:[],
					gives:[],
					realAmout: 0,
					discountAmount: 0,
					userMobile: '',
					appointmentId: 0,
					cardItemName: '',
					consumeAmout: 0,
					discountAmout: 0,
					schemeName: '',
				},
				rules: {
					userName:[{
						required: true,
						message: '请选择会员',
						trigger: ['blur', 'change']
					}],
					orderTypeName: [{
						required: true,
						message: '请选择订单类型',
						trigger: ['blur', 'change']
					}]
				}
			}
		},
		computed: { 
			...mapState(['store'])
		},
		onLoad(opt) {
			if(opt.id){
				this.isEdit = true
				this.getDetail(opt.id)
			}
			this.datetime = getDateTime.dateTimeStr('y/m/d h:i:s')
			this.form.storeId = this.store.id
			// 监听事件  
			uni.$on('client', obj => {
				this.form.userName = obj.nickName
				this.form.userMobile = obj.mobile
				this.form.userId = obj.id
				this.getOrderComponent()
			})
			uni.$on('add-pct', obj => {
				this.form.items = obj
				this.realAmout = obj.reduce((acc, cur) => {
					return acc + cur.price * cur.nums
				}, 0)
				this.form.realAmout = this.realAmout
				this.getOrderComponent()
			})
			uni.$on('select-staff', obj => {
				this.form.items[obj.index].staffId = obj.id
				this.form.items[obj.index].staffName = obj.nickName
			})
			uni.$on('select-saler', obj => {
				this.form.items[obj.index].salerId = obj.id
				this.form.items[obj.index].salerName = obj.nickName
				this.$forceUpdate()
			})
			uni.$on('gift', list => {
				const itemMap = {};
				const array1 = this.form.gives
				const array2 = list
				// 构建哈希表
				array1.forEach(item => {
				  itemMap[item.itemId] = item;
				});
				array2.forEach(item => {
				  const existingItem = itemMap[item.itemId];
				  if (existingItem) {
				    existingItem.nums += item.nums;
				  } else {
				    array1.unshift(item);
				  }
				});
				this.form.gives = array1 
			})
		},
		onUnload() {// 移除监听事件  
			uni.$off('client')
			uni.$off('add-pct')
			uni.$off('select-staff')
			uni.$off('select-saler')
			uni.$off('gift')
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules)
		},
		methods: {
			onChangePnm(ix, e){
				this.form.items[ix].nums = e.value
				this.realAmout = this.form.items.reduce((acc, cur) => {
					return acc + cur.price * cur.nums
				}, 0)
				this.form.realAmout = this.realAmout
				// this.getOrderComponent()
			},
			setGiftNums(e){
				if(e.value === 0){
					this.form.gives.splice(e.name, 1)
				}
			},
			getOrderComponent(){
				if(!uni.$u.test.isEmpty(this.form.userId) && this.form.items.length !== 0){
					this.$reqJsonPost('GetOrderComponent', {
						userId: this.form.userId,
						orderType: this.form.orderType,
						items: this.form.items.map((im, ix)=>{
							im.recordId = ix
							return im
						})
					}).then(res=>{
						this.form.cardItemName = res.data.orderComponentReq.cardItemName || '',
						this.form.consumeAmout = res.data.orderComponentReq.consumeAmout || 0,
						this.form.discountAmout = res.data.orderComponentReq.discountAmout || 0,
						this.form.schemeName = res.data.orderComponentReq.schemeName || '',
						this.realAmout = res.data.orderComponentReq.oughtAmount
						this.form.realAmout = this.realAmout - this.form.discountAmount
						this.form.items = this.form.items.map((im, ix)=>{
							im.projectOrderItemId = res.data.orderItems[ix].projectOrderItemId
							im.salerId = ''
							im.salerName = ''
							return im
						})
					})
				}
			},
			getDetail(id){
				this.$reqJsonPost('StoreStaffDoSetisGetDetails', { id: id }).then(res=>{
					this.form = {
						userName: res.data.userName,
						userId: res.data.userId,
						storeId: this.store.id,
						orderType: 11,
						orderTypeName: '项目',
						remark:res.data.remark,
						appointmentId: id,
						items:[{
							name:res.data.projectName,
							itemId: res.data.projectId,
							nums: 1,
							price: res.data.price,
							staffId: res.data.staffId,
							staffName: res.data.staffName,
							appointmentTime:res.data.appointmentTime,
							salerName:'',
							salerId: 0
						}],
						gives: res.data.gives,
						realAmout: res.data.price,
						discountAmount: 0,
						userMobile: res.data.userPhone,
					}
					this.getOrderComponent()
				})
			},
			setDiscountAmount(price){
				this.form.realAmout = this.realAmout - price >= 0? this.realAmout - price: 0
			},
			onConfirmDataTime(e){
				this.form.items[this.dtIndex].appointmentTime = uni.$u.timeFormat(e.value, 'yyyy-mm-dd hh:MM')
				this.showTimePicker = false
			},
			setDate(ix){
				this.Dix = ix
				this.showDatePicker=true
			},
			onConfirmData(e){
				this.form.gives[this.Dix].validityDate = uni.$u.timeFormat(e.value, 'yyyy-mm-dd')
				this.showDatePicker = false
			},
			selDataTime(ix){
				this.dtIndex = ix
				this.showTimePicker = true
			},
			addOrderItems(){
				if(this.isEdit) return 
				if(this.form.orderType == null){
					this.$refs.uToast.show({ message:'请先选择订单类型!' })
				}else {
					if(this.form.orderType === 11){
						uni.$u.route('/pages/selectPage/project',{ items:JSON.stringify(this.form.items),type: '2' })
					}else if(this.form.orderType === 1){
						uni.$u.route('/pages/selectPage/goods',{ items:JSON.stringify(this.form.items) })
					}else if(this.form.orderType === 12){
						uni.$u.route('/pages/selectPage/card',{ items:JSON.stringify(this.form.items) })
					}
				}
			},
			changeOT(e) {
				this.form.orderType = e.value[0].value
				this.form.orderTypeName = e.value[0].name
				this.form.items = []
				this.showOT = false
			},
			// 提交
			submit() {
				let that = this
				this.$refs.uForm.validate().then(res => {
					if(that.form.items.length > 0){
						if(that.form.orderType === 11){
							const index = that.form.items.findIndex(im=> uni.$u.test.isEmpty(im.staffId))
							if(index !== -1){
								uni.$u.toast('请选择服务人员')
								return
							}
						}
						let subd = that.form
						let items = that.form.items
						let simData = {
							userId: subd.userId,
							storeId: subd.storeId,
							orderType: subd.orderType,
							realAmout:subd.realAmout,
							discountAmount: subd.discountAmount,
							remark: subd.remark,
							appointmentId: subd.appointmentId,
							items: items.map(im=>{
								return {
									itemId: im.itemId,
									nums: im.nums,
									price: im.price,
									staffId: im.staffId || 0,
									salerId: im.salerId || 0,
									appointmentTime: im.appointmentTime || '',
									projectOrderItemId: im.projectOrderItemId
								}
							}),
							gives: subd.gives,
						}
						that.$reqJsonPost('CoreCmsOrderCreate', simData).then(res=>{
							if(res.code === 0){
								if(subd.orderType === 12){
									uni.redirectTo({
										url: `/pages/payment/qrc?id=${res.data}&&pages=/pages/order/list/cardEntryList&&orderType=${subd.orderType}`
									});
								}else if(subd.orderType === 1){
									uni.redirectTo({
										url: `/pages/payment/qrc?id=${res.data}&&pages=/pages/order/list/productList&&orderType=${subd.orderType}`
									});
								}else if(subd.orderType === 11){
									if(res.otherData.payStatus===2){
											uni.redirectTo({
												url: '/pages/order/list/projectList?status=5'
											});
									}else {
										uni.redirectTo({
											url: `/pages/payment/qrc?id=${res.data}&&pages=/pages/order/list/projectList&&orderType=${subd.orderType}`
										})
									}
									
								}
								// that.$reqJsonPost('CoreCmsOrderPayQrCode',{orderType: subd.orderType, orderId: res.data}).then(res=>{
								// 	// uni.$u.route('/pages/payment/qrc', {url: res.data})
								// })
							}
						})
					} else {
						uni.$u.toast('请选择开单项目')
					}
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.gap {
		padding: 20rpx;
		color: #aaa;
		font-size: 28rpx;
	}

	.ubtn {
		padding: 0 40rpx;
		margin-top: 40rpx;
		padding-bottom: 0;  
		padding-bottom: constant(safe-area-inset-bottom);  
		padding-bottom: env(safe-area-inset-bottom);  
	}

	.tag-box {
		display: flex;
		flex-wrap: wrap;
		margin-top: 20rpx;
		padding-top: 20rpx;
		border-top: 1px #d6d7d9 solid;

		// justify-content: space-around;
		.tag-item {
			border: 1px #d6d7d9 solid;
			text-align: center;
			// width: 160rpx;
			padding: 10rpx 10rpx;
			border-radius: 10rpx;
			margin-bottom: 20rpx;
			margin-right: 20rpx;
		}

		.tag-active {
			border-color: #fa3534;
			color: #fa3534;
		}

		.tag-active2 {
			background-color: #d6d7d9;
			color: #999;
		}
	}
	.minus {
			width: 22px;
			height: 22px;
			border-width: 1px;
			border-color: #E6E6E6;
			border-style: solid;
			border-top-left-radius: 100px;
			border-top-right-radius: 100px;
			border-bottom-left-radius: 100px;
			border-bottom-right-radius: 100px;
			@include flex;
			justify-content: center;
			align-items: center;
		}
	
		.input {
			padding: 0 20rpx;
		}
	
		.plus {
			width: 22px;
			height: 22px;
			background-color: #FF0000;
			border-radius: 50%;
			/* #ifndef APP-NVUE */
			display: flex;
			/* #endif */
			justify-content: center;
			align-items: center;
		}
</style>
